<template>
  <div class="main-container">
    <!-- <div class="span9">
      <ul class="breadcrumb">
        <li><a href="/">首页</a> <span class="divider">/</span></li>
        <li class="active"> 购物车</li>
      </ul>
    </div>
    <h3 class="xuangou"><a href="/product">继续选购</a></h3>
    <hr class="soft" /> -->
    <el-row style="padding-top: 20px">
      <el-col :offset="18" :span="2">
        <div style="line-height:40px;font-weight: bold;color:#065b2b">{{ price }}￥</div>
      </el-col>
      <el-col :span="2">
        <el-button :disabled="selectedCartList.length === 0" round style="width: 100%" @click="handleOrderCreate">结算</el-button>
      </el-col>
    </el-row>
    <el-table :data="cartList" class="cart-table" @selection-change="handleSelectionChange" :row-key="getRowKeys">
      <el-table-column
        type="selection"
        width="55"
        :reserve-selection="true">
      </el-table-column>
      <el-table-column label="产品" prop="img">
        <template slot-scope="scope">
          <el-image style="width: 100px; height: 100px" :src="scope.row.img" fit="contain"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="描述" prop="title"></el-table-column>
      <el-table-column label="单价" prop="n_price">
        <template slot-scope="scope">
          <span>{{ scope.row.n_price }} 元</span>
        </template>
      </el-table-column>
      <el-table-column label="数量" prop="amount">
        <template slot-scope="scope">
          <el-button icon="el-icon-plus" size="mini" circle @click="updateAmount(scope.row, 1)"></el-button>
          <span style="padding: 0 20px">{{ scope.row.amount }}</span>
          <el-button icon="el-icon-minus" size="mini" circle @click="updateAmount(scope.row, -1)"></el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- <div class="titles">
      <p>产品</p>
      <p>描述</p>
      <p>单价</p>
      <p class="he">数量/更新</p>
      <p>操作</p>
    </div>
    <div class="cart-item" v-for="(item, index) in cartList" :key="index">
      <p class="item-name"><img :src="item.img" alt="" /></p>
      <p>{{ item.title }}</p>
      <p class="item-price">{{ item.n_price }} 元</p>
      <button class="increment-btn he" @click="updateAmount(item, 1)">+</button>
      <span class="quantity he" style="text-align: center;">{{ item.amount }}</span>
      <button class="decrement-btn he" @click="updateAmount(item, -1)">-</button>
      <p>包邮</p>
    </div> -->
    <el-dialog title="结算" :visible.sync="openOrderDialog" >
      <el-form ref="orderForm" label-position="top" :model="orderForm" :rules="orderRules">
        <el-form-item prop="addr_id">
          <el-select v-model="orderForm.addr_id" placeholder="请选择收货地址" style="width:100%" >
            <el-option
              style="height: 100px;"
              v-for="addr in addrList"
              :key="addr.addr_id"
              :label="addr.name + addr.phone_number"
              :value="addr.addr_id">
              <el-row>
                <el-col :span="12">
                  <span style="float: left">{{ addr.name }}</span>
                </el-col>
                <el-col :span="12">
                  <span style="float: right">{{ addr.phone_number }}</span>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <span>{{ addr.address }}</span>
                </el-col>
              </el-row>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      
      <el-table :data="selectedCartList">
        <el-table-column label="产品" prop="img">
          <template slot-scope="scope">
            <el-image style="width: 100px; height: 100px" :src="scope.row.img" fit="contain"></el-image>
          </template>
        </el-table-column>
        <el-table-column label="描述" prop="title"></el-table-column>
        <el-table-column label="单价" prop="n_price">
          <template slot-scope="scope">
            <span>{{ scope.row.n_price }} 元</span>
          </template>
        </el-table-column>
        <el-table-column label="数量" prop="amount"></el-table-column>
        <el-table-column label="小计">
          <template slot-scope="scope">
            <span>{{ scope.row.n_price * scope.row.amount }} 元</span>
          </template>
        </el-table-column>
        
      </el-table>
      <div style="line-height:40px;font-weight: bold;color:#065b2b;text-align: right;">合计{{price}}￥</div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="openOrderDialog = false">取 消</el-button>
        <el-button type="primary" @click="submitOrderForm">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="支付" :visible.sync="openPayDialog" @close="handlePaid">
      <img style="margin: auto;display: block;" :src="pay.qrcode"/>
      <div style="text-align: center;font-size: 40px;font-weight: bold;color: #065b2b;">{{ pay.price }} ¥</div>
    </el-dialog>
  </div>
</template>
<script>
import { listCart, updateCart, deleteCart } from '@/api/cart'
import { listAddr } from '@/api/addr'
import { createOrder, payOrder, paidOrder } from '@/api/order'

export default {
  name: 'ShoppingCart',
  data() {
    return {
      price: 0,
      openPayDialog: false,
      openOrderDialog: false,
      selectedCartIdArr: [],
      cartList: [],
      selectedCartList: [],
      addrList: [],
      addrId: null,
      orderForm: {},
      orderRules: {
        addr_id: [
          { required: true, message: '请选择收获地址', trigger: 'blur' }
        ]
      },
      pay: {}
    }
  },
  created() {
    this.getList()
  },
  methods: {
    handleSelectionChange(selection) {
      this.selectedCartIdArr = selection.map(item => item.cart_id)
      this.calPrice()
    },
    getRowKeys(row) {
      return row.cart_id;
    },
    calPrice() {
      this.price = 0
      if (this.cartList !== null && this.cartList.length > 0) {
        this.selectedCartList = this.cartList.filter(cart => this.selectedCartIdArr.includes(cart.cart_id))
        this.selectedCartList.forEach(cart => this.price += cart.amount * cart.n_price)
      }
    },
    handleOrderCreate() {
      this.orderForm = {
        addr_id: null,
        cart_id_array: this.selectedCartIdArr,
      }
      this.openOrderDialog = true
      this.getAddrList()
    },
    getList() {
      listCart().then(res => {
        this.cartList = res.data
        this.calPrice()
      })
    },
    getAddrList() {
      listAddr().then(res => {
        this.addrList = res.data
        for (const addr of this.addrList) {
          if (addr.is_default === 1) {
            this.orderForm.addr_id = addr.addr_id
          }
        }
      })
    },
    submitOrderForm() {
      this.$refs['orderForm'].validate((valid) => {
        if (valid) {
         createOrder(this.orderForm).then(res => {
            if (res.code === 200) {
              this.openOrderDialog = false
              const order_id = res.data.order_id
              console.log('order_id: ', order_id)
              this.handleOrderPay(order_id)
            } else {
              this.$message({
                message: res.msg,
                type: 'error',
                duration: 300
              })
            }
          })
        }
      })
    },
    updateAmount(cart, amount) {
      if (amount < 0 && cart.amount <= 1) {
        this.$message({
          message: "商品数量最少为1",
          type: 'error',
          duration: 1000
        })
        return
      }
      const data = {
        cart_id: cart.cart_id,
        amount: cart.amount + amount
      }
      updateCart(data).then(res => {
        this.getList()
      })
    },
    handleDelete(cart) {
      const cart_id = cart.cart_id
      this.$confirm('是否确认删除', '确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteCart(cart_id).then(res => {
          this.$message({
            message: "删除成功",
            type: 'success',
            duration: 1000
          })
          this.getList()
        })
      }).catch(() => {});
    },
    handleOrderPay(order_id) {
      payOrder(order_id).then(res => {
        if (res.code === 200) {
          this.pay = res.data
          this.openPayDialog = true
        } else {
          this.$message({
            message: res.msg,
            type: 'error',
            duration: 300
          })
        }
      })
    },
    handlePaid() {
      this.$confirm('是否已完成支付', '确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        paidOrder(this.pay.order_id).then(res => {
          this.getList()
        })
      }).catch(() => {});
    },
  }
}
</script>
<style>
.cart-table {
  min-height: 600px;
  padding: 20px 100px;
}
</style>
